//
//  UpdateViewController.m
//  Daybook
//
//  Created by dllo on 16/5/21.
//  Copyright © 2016年 zhangbin. All rights reserved.
//

#import "UpdateViewController.h"
#import "Common.h"

@interface UpdateViewController ()<AddViewDelegate,EditViewControllerDelegate>

@property (nonatomic, strong) UISegmentedControl *seg;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, assign) BOOL isChange;
@end
@implementation UpdateViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.hidesBackButton = YES;
    //self.str = @"".mutableCopy;
    NSLog(@"#####%@", _str);
    
    NSString *string = [_addView.textField.text substringFromIndex:1];
    if (![_str isEqualToString:string] && ![string isEqualToString:@"0.00"]) {
        _str = [NSMutableString stringWithString:string];
    }
    
    _addView.str = _str;
    _addView.isClick = NO;
    self.topView.hidden = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    _addView.index = 1000;
    _addView.type = _type;
    
    if ([_type isEqualToString:@"1"]) {
        _seg.selectedSegmentIndex = 0;
        _addView.isState = 0;
    }
    else {
        _seg.selectedSegmentIndex = 1;
        _addView.isState = 1;
    }
    
    //_addView.picName = self.picName;
    _addView.moneyStr = _str;

    _addView.isAgain = 1;
    
    [_addView.textField becomeFirstResponder];
    
    if (![self.picName isEqualToString:_addView.picName] && (_addView.picName == nil)) {
        
        if ([_type isEqualToString:@"1"]) {
            _seg.selectedSegmentIndex = 0;
            _addView.isState = 0;
        }
        else {
            _seg.selectedSegmentIndex = 1;
            _addView.isState = 1;
        }
        
    }
    _addView.picName = self.picName;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.navigationItem.hidesBackButton = NO;
    self.topView.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    [self createView];
}

- (void)createView {
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 5, MAIN_WIDTH, MAIN_HEIGHT / 20)];
    [self.navigationController.navigationBar addSubview:_topView];
    
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"收入", @"支出"]];
    _seg.selectedSegmentIndex = 1;
    _seg.frame = CGRectMake(0, 0, MAIN_WIDTH / 3, MAIN_HEIGHT / 25);
    _seg.center = CGPointMake(_topView.center.x, MAIN_HEIGHT / 40);
    [_topView addSubview:_seg];
    [_seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    _seg.tintColor = [UIColor orangeColor];
    self.addView = [[AddView alloc] initWithFrame:self.view.frame];
    _addView.delegate = self;
    [self.view addSubview:_addView];
    
}
- (void)segAction:(UISegmentedControl *)seg {
    self.isChange = 1;
    _addView.isChange = _isChange;
    
    if (seg.selectedSegmentIndex == 1) {
        _addView.isState = YES;
    }
    else {
        _addView.isState = NO;
    }
}

- (void)setStr:(NSMutableString *)str {
    _str = str;
    
}

- (void)popViewActionPic:(NSString *)pic describe:(NSString *)describe price:(NSString *)price {
    // 返回前一页
    CATransition *backPageAnimation = [CATransition animation];
    backPageAnimation.duration = 0.5;
    backPageAnimation.type = kCATransitionMoveIn;
    backPageAnimation.subtype = kCATransitionFromTop;
    
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.view.layer addAnimation:backPageAnimation forKey:nil];
    [self.navigationController popToRootViewControllerAnimated:NO];
//    NSLog(@"111111111111111111%d", _isEdit);
    if (_isEdit == NO) {
        if (price != nil) {
            if (_seg.selectedSegmentIndex == 1) {
                NSLog(@"支出");
                
                RLMRealm *realm = [RLMRealm defaultRealm];
                
                RLMResults *result = [RealmTool getCurrentAccountFromUserDefaults];
                DayBook *currentDayBook = [result firstObject];
                RLMResults *accountBook = [currentDayBook.bookContent objectsWhere:@"time = %@", self.time];
                Account *accountBookModel = accountBook[0];
                [realm beginWriteTransaction];
                
                
                
                accountBookModel.picName = pic;
                accountBookModel.name = describe;
                accountBookModel.remarks = self.remarks;
                accountBookModel.imageData = UIImagePNGRepresentation(self.image);
                NSMutableString *priceStr = [NSMutableString stringWithString:price];
                [priceStr substringFromIndex:1];
//                NSLog(@"%@",priceStr);
                accountBookModel.money = (NSNumber *)priceStr;
//                NSLog(@"%@",price);
                accountBookModel.type = @"2";
                accountBookModel.income = 0;
                //accountBookModel.time = [NSDate dateWithTimeIntervalSinceNow:0];
                
                [realm commitWriteTransaction];

                [[NSNotificationCenter defaultCenter] postNotificationName:@"moneyChanged" object:nil];
                
                
            }
            else {
                NSLog(@"收入");
                
                RLMRealm *realm = [RLMRealm defaultRealm];
                
                RLMResults *result = [RealmTool getCurrentAccountFromUserDefaults];
                DayBook *currentDayBook = [result firstObject];
                RLMResults *accountBook = [currentDayBook.bookContent objectsWhere:@"time = %@", self.time];
                

                Account *accountBookModel = accountBook[0];
                [realm beginWriteTransaction];
                
                
                
                accountBookModel.picName = pic;
                accountBookModel.name = describe;
                
                
                
                accountBookModel.money = 0;
                
                accountBookModel.type = @"1";
                NSMutableString *priceStr = [NSMutableString stringWithString:price];
                [priceStr substringFromIndex:1];
                
                accountBookModel.income = (NSNumber *)priceStr;
                //accountBookModel.time = [NSDate dateWithTimeIntervalSinceNow:0];
                accountBookModel.remarks = self.remarks;
                accountBookModel.imageData = UIImagePNGRepresentation(self.image);
                [realm commitWriteTransaction];
                

                NSString *dataString = [self stringFromDate:accountBookModel.time];
                
                
                NSLog(@"%@", [NSString stringWithFormat:@"%@", accountBookModel.time]);
                NSLog(@"%@", dataString);
                [[NSNotificationCenter defaultCenter] postNotificationName:@"incomeChanged" object:nil];
                
            }
            
        }
    }
    else {
        //将要替换
//        NSLog(@"%@", _editTime);
        if (price != nil) {
            if (_seg.selectedSegmentIndex == 1) {
                NSLog(@"支出");
                
                //AccountBook *accountBook = [[AccountBook alloc]init];
                RLMRealm *realms = [RLMRealm defaultRealm];
                //                RLMResults<AccountBook *> *accountBook = [AccountBook objectsInRealm:realm where:@"time = %@", self.time];
                
                RLMResults *result = [RealmTool getCurrentAccountFromUserDefaults];
                DayBook *currentDayBook = [result firstObject];
                RLMResults *accountBook = [currentDayBook.bookContent objectsWhere:@"time = %@", _editTime];
//                NSLog(@"支出: %@", accountBook);
                Account *accountBookModel = accountBook[0];
                [realms beginWriteTransaction];
                
                
                
                accountBookModel.picName = pic;
                accountBookModel.name = describe;
                accountBookModel.remarks = self.remarks;
                accountBookModel.imageData = UIImagePNGRepresentation(self.image);
                NSMutableString *priceStr = [NSMutableString stringWithString:price];
                [priceStr substringFromIndex:1];
                NSLog(@"%@",priceStr);
                accountBookModel.money = (NSNumber *)priceStr;
                NSLog(@"%@",price);
                accountBookModel.type = @"2";
                accountBookModel.income = 0;
                //accountBookModel.time = [NSDate dateWithTimeIntervalSinceNow:0];
                
                [realms commitWriteTransaction];
//                NSLog(@"支出完成编辑: %@", accountBook);
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"moneyChanged" object:nil];
                
                
            }
            else {
//                NSLog(@"%@", _editTime);
                
                RLMRealm *realms = [RLMRealm defaultRealm];
                //                RLMResults<AccountBook *> *accountBook = [AccountBook objectsInRealm:realm where:@"time = %@", self.time];
                
                RLMResults *result = [RealmTool getCurrentAccountFromUserDefaults];
                DayBook *currentDayBook = [result firstObject];
                RLMResults *accountBook = [currentDayBook.bookContent objectsWhere:@"time = %@", _editTime];
                
//                NSLog(@"收入: %@", accountBook);
                
                Account *accountBookModel = accountBook[0];
                //                AccountBook *accountBookModel = accountBook[0];
                [realms beginWriteTransaction];
                
                
                
                accountBookModel.picName = pic;
                accountBookModel.name = describe;
                
                
                
                accountBookModel.money = 0;
                
                accountBookModel.type = @"1";
                NSMutableString *priceStr = [NSMutableString stringWithString:price];
                [priceStr substringFromIndex:1];
                
                accountBookModel.income = (NSNumber *)priceStr;
                //accountBookModel.time = [NSDate dateWithTimeIntervalSinceNow:0];
                accountBookModel.remarks = self.remarks;
                accountBookModel.imageData = UIImagePNGRepresentation(self.image);
                [realms commitWriteTransaction];
                
//                NSLog(@"收如完成编辑: %@", accountBook);
                
//                NSString *dataString = [self stringFromDate:accountBookModel.time];
                
                
//                NSLog(@"%@", [NSString stringWithFormat:@"%@", accountBookModel.time]);
//                NSLog(@"%@", dataString);
                [[NSNotificationCenter defaultCenter] postNotificationName:@"incomeChanged" object:nil];
                
            }
            
        }

        
    }
    _isEdit = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"rightViewExchangeAccountBook" object:nil];
}



//NSDate转NSString
- (NSString *)stringFromDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    //    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd:hh:mm:ss"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    return destDateString;
}


- (void)jumpToEditView {
    EditViewController *editVC = [EditViewController new];
    [self.navigationController pushViewController:editVC animated:YES];
    editVC.remarks = self.remarks;
    editVC.picImage = self.image;
    editVC.delegate = self;
}

- (void)sendpic:(UIImage *)pic remarks:(NSString *)remarks {
    if (_image != pic) {
        _image = pic;
    }
    if (_remarks != remarks) {
        _remarks = remarks;
    }
}




@end
